package com.anjubao.parking.municipal.roadside.task;

import com.anjubao.parking.municipal.common.utils.RedisClientTemplate;
import com.anjubao.parking.municipal.roadside.constant.DeviceIsOnlineEnum;
import com.anjubao.parking.municipal.roadside.constant.DeviceStatusEnum;
import com.anjubao.parking.municipal.roadside.model.DeviceStatus;
import com.anjubao.parking.municipal.roadside.service.DeviceStatusService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.ZSetOperations;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.List;
import java.util.Set;


/**
 *
 *
 * @author anjubao
 */
@Component
public class RedisTask {

    @Value("${range:1000}")
    private String range;

    @Autowired
    private RedisClientTemplate redisClientTemplate;

    @Autowired
    private DeviceStatusService deviceStatusService;
    /**
     *ZADD device_last_update_time  当前时间戳() ${deviceId}
     *
     * score  member
     * 123   123123123123
     * 122   123123123122
     * 121   123123123121
     * 120   123123123120
     *
     *
     * ZREVRANGEBYSCORE device_last_update_time now-2 0
     * [0-(now-2)]
     *
     *
     * set device_is_online:{deviceId}=0\
     * zrem device_last_update_time  ${deviceId}
     *
     *
     * zrange 从小到大
     * zrevrange 从大到小
     */
    @Scheduled(cron = "${task.cron}")
    public void refreshParkingLot() {
        Set<String> typedTupleSet =  this.redisClientTemplate.getOpsForZSet().rangeByScore("device_last_update_time",System.currentTimeMillis()-Long.valueOf(range),System.currentTimeMillis());
        for (String devId : typedTupleSet) {
            this.redisClientTemplate.getOpsForZSet().remove("device_last_update_time",devId);
            DeviceStatus deviceStatus=deviceStatusService.getById(devId);
            deviceStatus.setStatus(DeviceIsOnlineEnum.OffLine.getCode());
            deviceStatusService.updateById(deviceStatus);
        }
    }



}
